package com.zdkj.subway.stm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.in.CommomConfirmInfoDTO;
import com.zdkj.subway.stm.dto.in.SwStConductorSettleDto;
import com.zdkj.subway.stm.entity.SwStConductorSettle;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStConductorSettleMapper;
import com.zdkj.subway.stm.mapper.SwStMarketingTicketGroupSellMapper;
import com.zdkj.subway.stm.mapper.SwStMarketingTicketMapper;
import com.zdkj.subway.stm.mapper.SwStMarketingTicketOffineSellMapper;
import com.zdkj.subway.stm.service.*;
import com.zdkj.subway.stm.shouRuJs.BomUtil;
import com.zdkj.subway.stm.util.BeanUtilsStm;
import com.zdkj.subway.stm.util.DateFormat;
import com.zdkj.subway.stm.util.JdbcUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 售票员结算表（主表）
 *
 * @author chenbo
 * @date 2020-02-01 19:24:00
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstconductorsettle")
@Api(value = "swstconductorsettle", tags = "售票员日结算表（主表）管理")
@Slf4j
public class SwStConductorSettleController {

    private final SwStConductorSettleService swStConductorSettleService;
    private final SwStConductorSettleMapper swStConductorSettleMapper;

    private final SwStTicketPettyAddService swStTicketPettyAddService;
    private final SwStTicketPettyAddDetailsService swStTicketPettyAddDetailsService;

    private final SwStInputPassengerWorkTicketService swStInputPassengerWorkTicketService;

    private final SwStMarketingTicketGroupSellMapper swStMarketingTicketGroupSellMapper;
    private final SwStMarketingTicketOffineSellMapper swStMarketingTicketOffineSellMapper;

    private final SwStMarketingTicketMapper swStMarketingTicketMapper;

    private final SystemUserService systemUserService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;

    /**
     * 分页查询
     *
     * @param page                分页对象
     * @param swStConductorSettle 售票员结算表（主表）
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStConductorSettlePage(Page page, SwStConductorSettle swStConductorSettle) {
        SwStConductorSettle swswStConductorSettletObj = ObjectUtils.getDefaultObj(SwStConductorSettle.class);

		String lineCode = swswStConductorSettletObj.getLineCode();
        String stationCode = swswStConductorSettletObj.getStationCode();

        swStConductorSettle.setLineCode(lineCode);
        swStConductorSettle.setStationCode(stationCode);
        String startDateCondition = swStConductorSettle.getWorkingStartTimeDTO();
        String endDateCondigiton = swStConductorSettle.getWorkingEndTimeDTO();
        String conductorJobNo = swStConductorSettle.getConductorJobNo();
        swStConductorSettle.setConductorJobNo(null);//先置空，下面的查询才能起作用
		swStConductorSettle.setConductorName(null);
        //LambdaQueryWrapper<SwStConductorSettle> queryWrapper = Wrappers.query(swStConductorSettle).lambda();
        //QueryWrapper<SwStConductorSettle> queryWrapper = Wrappers.query(swStConductorSettle);
        QueryWrapper<SwStConductorSettle> queryWrapper = Wrappers.query(swStConductorSettle);
        queryWrapper.orderByDesc("WORKING_START_TIME");
        if(StringUtils.isNotEmpty(swStConductorSettle.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().eq(SwStConductorSettle::getConductorJobNo,conductorJobNo);//报表路径跳转
        }
        if(StringUtils.isEmpty(swStConductorSettle.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().like(SwStConductorSettle::getConductorJobNo,conductorJobNo);//售票员工号模糊匹配
        }
		/*没用到这个参数
        if (StringUtils.isNotBlank(startDateCondition)) {
            queryWrapper.lambda().likeRight(SwStConductorSettle::getWorkingStartTime, startDateCondition);
        }
        if (StringUtils.isNotBlank(endDateCondigiton)) {
            queryWrapper.lambda().likeRight(SwStConductorSettle::getWorkingEndTime, endDateCondigiton);
        }*/

		IPage<SwStConductorSettle> iPage = swStConductorSettleService.page(page, queryWrapper);
		
		//如果分页里有数据，且有线路站点等数据，再提醒车站进行合并
		if(StringUtils.isNotEmpty(lineCode) && StringUtils.isNotEmpty(stationCode) && iPage!=null && iPage.getRecords()!=null && iPage.getRecords().size()>0){
		   String sql = "select a.id from sw_st_conductor_settle a\n"+
					"where \n"+
					"line_code='"+lineCode+"' and station_code='"+stationCode+"' \n"+
					"and del_flag='0' and APPROVAL_STATUS='0' \n"+
					"and is_merge='0' \n"+
					"and\n"+
					"(a.device_operate_num,a.SETTLE_TIME) \n"+
					"in (\n"+
					"select device_operate_num,SETTLE_TIME \n"+
					"from sw_st_conductor_settle \n"+
					"where line_code='"+lineCode+"' and station_code='"+stationCode+"' \n"+
					"and del_flag='0' and APPROVAL_STATUS='0' \n"+
					"and is_merge='0' \n"+
					"group by device_operate_num,SETTLE_TIME having count(*) > 1\n"+
					") ";
			try{
				List<Map<String,Object>> lstMaps = JdbcUtil.exeSqlQuery(sql);
				List<Integer> lstIds = new ArrayList();
				if(lstMaps!=null && lstMaps.size()>0){
					for(int i=0;i<lstMaps.size();i++){					
						Map<String,Object> map = lstMaps.get(i);
						lstIds.add(Integer.valueOf(String.valueOf(map.get("id"))));					
					}        	
				}
				List<SwStConductorSettle>  list = iPage.getRecords();
				for(SwStConductorSettle condcutorSettle:list){
					if(lstIds.contains(condcutorSettle.getId())){
						condcutorSettle.setIsNeedMerge("1");
					}else{
					   condcutorSettle.setIsNeedMerge("0");
					}       		
				}  
			}catch(SQLException e){
			
			}
			
		
		}
		
        return R.ok(iPage);
    }


    /**
     * 通过id查询售票员结算表（主表）
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStConductorSettleService.getById(id));
    }

    /**
     * 新增售票员结算表（主表）
     *
     * @param swStConductorSettle 售票员结算表（主表）
     * @return R
     */
    @ApiOperation(value = "新增售票员结算表（主表）", notes = "新增售票员结算表（主表）")
    //@SysLog("新增售票员结算表（主表）")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_add')")
    public R save(@RequestBody SwStConductorSettle swStConductorSettle) {
        QueryWrapper queryWrapper=new QueryWrapper();
        PigxUser user = SecurityUtils.getUser();
        queryWrapper.eq("line_code",user.getLineCode());
        queryWrapper.eq("station_code",user.getStationCode());
        queryWrapper.eq("conductor_job_no",swStConductorSettle.getConductorJobNo());
        queryWrapper.eq("device_operate_num",swStConductorSettle.getDeviceOperateNum());
        queryWrapper.eq("conductor_shifts",swStConductorSettle.getConductorShifts());
        queryWrapper.eq("settle_time",swStConductorSettle.getSettleTime());
        queryWrapper.eq("del_flag","0");
        int conductorSettle=swStConductorSettleService.count(queryWrapper);
        if(conductorSettle>0){
            return R.failed(conductorSettle,swStConductorSettle.getConductorName()+"在"+swStConductorSettle.getSettleTime()+" 数据已存在！");
        }
        swStConductorSettle.setApprovalStatus("0");
        swStConductorSettle.setConfirmStatus("0");
        SwStConductorSettle defaultObj = ObjectUtils.getDefaultObj(SwStConductorSettle.class);
        BeanUtil.copyProperties(defaultObj, swStConductorSettle, CopyOptions.create().setIgnoreNullValue(true));
        swStConductorSettle.setBomCode(BeanUtilsStm.bomOrJobNoSort(swStConductorSettle.getBomCode()));//bom编号排序后新增
        //设备操作号去空格
        swStConductorSettle.setDeviceOperateNum(BeanUtilsStm.strRemoveBlank(swStConductorSettle.getDeviceOperateNum()));
        return R.ok(swStConductorSettleService.save(swStConductorSettle));
    }

    /**
     * 修改售票员结算表（主表）
     *
     * @param swStConductorSettle 售票员结算表（主表）
     * @return R
     */
    @ApiOperation(value = "修改售票员结算表（主表）", notes = "修改售票员结算表（主表）")
    //@SysLog("修改售票员结算表（主表）")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_edit')")
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody SwStConductorSettle swStConductorSettle) {
        SwStConductorSettle settle = swStConductorSettleService.getById(swStConductorSettle.getId());
        if(ObjectUtil.isNotEmpty(settle)){
            String approvalStatus = settle.getApprovalStatus();
            if("1".equals(approvalStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        QueryWrapper<SwStConductorSettle> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("line_code",swStConductorSettle.getLineCode());
        queryWrapper.eq("station_code",swStConductorSettle.getStationCode());
        queryWrapper.eq("conductor_job_no",swStConductorSettle.getConductorJobNo());
        queryWrapper.eq("device_operate_num",swStConductorSettle.getDeviceOperateNum());
        queryWrapper.eq("conductor_shifts",swStConductorSettle.getConductorShifts());
        queryWrapper.eq("settle_time",swStConductorSettle.getSettleTime());
        queryWrapper.eq("del_flag","0");
        queryWrapper.ne("id",swStConductorSettle.getId());
        int count=swStConductorSettleService.count(queryWrapper);
        if(count>0){
            return R.failed(count,swStConductorSettle.getConductorName()+"在"+swStConductorSettle.getSettleTime()+" 该班次的数据已存在,不允许修改为该售票员的数据！");
        }
        swStConductorSettle.setBomCode(BeanUtilsStm.bomOrJobNoSort(swStConductorSettle.getBomCode()));//bom编号排序后修改
        //设备操作号去空格
        swStConductorSettle.setDeviceOperateNum(BeanUtilsStm.strRemoveBlank(swStConductorSettle.getDeviceOperateNum()));
        PigxUser user = SecurityUtils.getUser();
        SwStConductorSettle conductorSettle = swStConductorSettleService.getById(swStConductorSettle.getId());
        if("1".equals(conductorSettle.getReportModifyStatus()) && ObjectUtil.isNotEmpty(conductorSettle)){
            conductorSettle.setEntryUpdateJobNo(user.getUserCode());
            conductorSettle.setEntryUpdateJobName(user.getNikeName());
            conductorSettle.setEntryUpdateTime(new Date());

            SwStmStationDataEntryLog swStmStationDataEntryLog = new SwStmStationDataEntryLog();
            swStmStationDataEntryLog.setRelationId(conductorSettle.getId());
            swStmStationDataEntryLog.setLogTableName(StmTableCommon.SW_ST_CONDUCTOR_SETTLE);
            swStmStationDataEntryLog.setLogInfo(JSONObject.toJSONString(conductorSettle));
            swStmStationDataEntryLog.setUpdateJobNo(user.getUserCode());
            swStmStationDataEntryLog.setUpdateJobName(user.getNikeName());
            swStmStationDataEntryLog.setUpdateTime(new Date());
            swStmStationDataEntryLogService.save(swStmStationDataEntryLog);
            if("1".equals(conductorSettle.getIsMerge())){
                swStConductorSettle.setConfirmStatus("1");
            }else{
			     swStConductorSettle.setApprovalStatus("0");
                 swStConductorSettle.setConfirmStatus("0");
			}
        }else{//修改之后改为未确认、未提交，防止之前确认后的情况。
		    swStConductorSettle.setApprovalStatus("0");
            swStConductorSettle.setConfirmStatus("0");
		}
        return R.ok(swStConductorSettleService.updateById(swStConductorSettle));
    }


    /**
     * 通过id查询乘售票员结算表（主表）历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询乘售票员结算表（主表）历史记录", notes = "通过id查询乘售票员结算表（主表）历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_CONDUCTOR_SETTLE));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                LogInfoList.add(jsonObject);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

//    /**
//     * 通过id删除售票员结算表（主表）
//     * @param id id
//     * @return R
//     */
//    @ApiOperation(value = "通过id删除售票员结算表（主表）", notes = "通过id删除售票员结算表（主表）")
//    @SysLog("通过id删除售票员结算表（主表）" )
//    @DeleteMapping("/{id}" )
//    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_del')" )
//    public R removeById(@PathVariable Integer id) {
//        return R.ok(swStConductorSettleService.removeById(id));
//    }

    /**
     * 新增售票员结算表和详情
     *
     * @param swStConductorSettleDto 售票员结算入参
     * @return R
     */
    @ApiOperation(value = "新增售票员结算表和详情", notes = "新增售票员结算表和详情")
    //@SysLog("新增或修改售票员结算表和详情")
    @PostMapping("/saveOrUpdateSettleAndDetail")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_cascade_add')")
    public R saveOrUpdateSettleAndDetail(@RequestBody SwStConductorSettleDto swStConductorSettleDto) {
        return R.ok(swStConductorSettleService.saveOrUpdateSettleAndDetail(swStConductorSettleDto));
    }

    /**
     * 新增售票员结算表和详情
     *
     * @param swStConductorSettleDto 售票员结算入参
     * @return R
     */
    @ApiOperation(value = "修改售票员结算表和详情", notes = "修改售票员结算表和详情")
    //@SysLog("修改售票员结算表和详情")
    @PostMapping("/updateSettleAndDetail")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_cascade_update')")
    public R UpdateSettleDetail(@RequestBody SwStConductorSettleDto swStConductorSettleDto) {
        return R.ok(swStConductorSettleService.updateSettleDetail(swStConductorSettleDto));
    }

    /**
     * 通过id删除售票员结算表 级联删除子表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除售票员结算表级联删除子表", notes = "通过id删除售票员结算表级联删除子表")
    //@SysLog("通过id删除售票员结算表级联删除子表")
    @DeleteMapping("/cascadeDel/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_cascade_del')")
    public R removeCascadeById(@PathVariable Integer id) {
        return R.ok(swStConductorSettleService.removeCascadeById(id));
    }

    /**
     * 批量删除子表
     *
     * @param idList
     * @return
     */
    //@SysLog("通过id批量删除售票员结算表级联删除子表")
    @DeleteMapping("/batchCascadeDel")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id批量删除售票员结算表级联删除子表", notes = "通过id批量删除售票员结算表级联删除子表")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStConductorSettle> list = swStConductorSettleService.list(new QueryWrapper<SwStConductorSettle>().lambda().in(SwStConductorSettle::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStConductorSettleService::removeById);
        return R.ok();
    }

    /**
     * 通过id级联查询售票员结算
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id级联查询售票员结算", notes = "通过id级联查询售票员结算")
    @GetMapping("/cascade/{id}")
    public R getCascadeById(@PathVariable("id") Integer id) {
        return R.ok(swStConductorSettleService.getCascadeById(id));
    }


    /**
     * 查询需要确认的数据
     *
     * @param confirmInfoDTO 查询需要确认的数据
     * @return R
     */
    @ApiOperation(value = "查询需要确认售票员日结数据的数据", notes = "查询需要确认售票员日结数据的数据")
    //@SysLog("查询需要确认售票员日结数据的数据")
    @PostMapping("/query/needConfirmData")
    public R queryNeedToConfirmData(@RequestBody CommomConfirmInfoDTO confirmInfoDTO) {
        return R.ok(swStConductorSettleService.queryNeedToConfirmData(confirmInfoDTO));
    }

    /**
     * 通过id确认售票员日结数据
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id确认售票员日结数据", notes = "通过id确认售票员日结数据")
    @GetMapping("/confirm/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_confirm')")
    public R confirmData(@PathVariable("id") Integer id) {
        return R.ok(swStConductorSettleService.confirmData(id));
    }
    /**
     * 通过客值一键确认售票员日结数据
     *
     * @param confirmInfoDTO confirmInfoDTO
     * @return R
     */
    @ApiOperation(value = "通过客值一键确认售票员日结数据", notes = "通过客值一键确认售票员日结数据")
    @PostMapping("/confirmAll")
    public R confirmAllData(@RequestBody CommomConfirmInfoDTO confirmInfoDTO) {
        return R.ok(swStConductorSettleService.confirmAllData(confirmInfoDTO));
    }
    /**
     * morning and evening classes
     *
     * @param page
     * @param swStConductorSettle
     * @param response
     */
    @ApiOperation(value = "导出售票员日结算数据", notes = "导出售票员日结算数据")
    @GetMapping("/export")
    public void export(Page page, SwStConductorSettle swStConductorSettle, HttpServletResponse response) {
        List<SwStConductorSettle> records = swStConductorSettleService.page(page, Wrappers.query(swStConductorSettle)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            //早晚班
            R<List<SysDictItem>> meClass = systemUserService.getDictByType(StmConstans.STM_MORNING_EVENING_CLASS);
            R<List<SysDictItem>> stmConductorShift = systemUserService.getDictByType(StmConstans.STM_CONDUCTOR_SHIFT);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                Map<String, String> meClassData = meClass.getData().stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                Map<String, String> stmConductorShiftMap = stmConductorShift.getData().stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStConductorSettle record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                    record.setMorningAndEveningShifts(meClassData.get(record.getMorningAndEveningShifts()));
                    record.setConductorShifts(stmConductorShiftMap.get(record.getConductorShifts()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("售票员日结算数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStConductorSettle.class).
                    sheet("售票员日结算数据").doWrite(records);
        } catch (IOException e) {
            log.error("售票员日结算数据导出失败");
        }
    }


    /**
     * 合并数据  对两条数据进行合并
     *
     * @param idList
     * @return
     */
    //@SysLog("合并数据 对两条日结算数据进行合并")
    @PostMapping("/merge")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_conductor_settle_merge')")
    @Transactional
    @ApiOperation(value = "合并数据", notes = "合并数据")
    public R mergeSellData(@RequestBody List<Integer> idList,String conductorShifts) {
        List<SwStConductorSettle> mergeDatList = swStConductorSettleService.list(new QueryWrapper<SwStConductorSettle>().lambda().in(SwStConductorSettle::getId, idList).eq(SwStConductorSettle::getApprovalStatus, CommonConstants.UN_SUBMIT));
        if (mergeDatList.size() < 2) {
            return R.failed("请选择两条数据");
        }
        //校验必须是一天的数据 并且是相同的设备操作号才能合并
        String deviceOperateNum = mergeDatList.get(0).getDeviceOperateNum();
        LocalDate localDate = mergeDatList.get(0).getWorkingStartTime().toLocalDate();
        for (SwStConductorSettle settle : mergeDatList) {
            if (!settle.getWorkingStartTime().toLocalDate().equals(localDate)) {
                return R.failed("开始时间和结束时间不是同一天，无法合并");
            }
            if (!settle.getDeviceOperateNum().equals(deviceOperateNum)) {
                return R.failed("设备操作号不是同一个操作号，无法合并");
            }
        }
        Boolean isFlag = false;
        return R.ok(swStConductorSettleService.mergeSellData(idList,conductorShifts,isFlag));
    }

    /**
     * 合并数据  对两条数据进行合并  审核补提交合并调用
     *
     * @param
     * @return
     */
    @PostMapping("/submissionMerge")
    @ApiOperation(value = "合并数据，审核待提交合并调用", notes = "合并数据，审核待提交合并调用")
    @Transactional
    public R submissionMerge(@RequestBody SwStConductorSettle settle,
                             @RequestParam("paramStar") String paramStar,
                             @RequestParam("idList") List<Integer> idList,
                             @RequestParam("conductorShifts") String conductorShifts,
                             @RequestParam("isFlag") Boolean isFlag,
                             @RequestParam("normal") Boolean normal) {
        try {
            boolean b = swStConductorSettleService.mergeSellData(idList, conductorShifts, isFlag);
            if(b){
                HashMap<String, String> map = new HashMap<>();
                //重新组织数据
                SwStConductorSettle merge = swStConductorSettleService.getOne(Wrappers.<SwStConductorSettle>lambdaQuery()
                        .eq(SwStConductorSettle::getLineCode, settle.getLineCode())
                        .eq(SwStConductorSettle::getStationCode, settle.getStationCode())
                        .eq(SwStConductorSettle::getDeviceOperateNum, settle.getDeviceOperateNum())
                        .eq(SwStConductorSettle::getSettleTime, settle.getSettleTime())
                        .eq(SwStConductorSettle::getIsMerge, "1")
                        .eq(SwStConductorSettle::getConfirmStatus, CommonConstants.CONFIRM)
                        .eq(SwStConductorSettle::getDelFlag, "0")
                );

                JSONObject param = (JSONObject) JSONObject.toJSON(merge);
    //            //营销车票
    //            BigDecimal marketTicketAmount=new BigDecimal(0);
    //            List<SwStMarketingTicket> marketingTickets = swStMarketingTicketMapper.selectList(new QueryWrapper<SwStMarketingTicket>()
    //                    .eq("OPERTOR_TIME",merge.getSettleTime())
    //                    .eq("LINE_CODE", merge.getLineCode())
    //                    .eq("STATION_CODE", merge.getStationCode())
    //                    .eq("CONDUCTOR_JOB_NO", merge.getConductorJobNo())
    //                    .eq("CONDUCTOR_SHIFTS", merge.getConductorShifts())
    //                    .eq("BOM_CODE", merge.getBomCode())
    //                    .eq("APPROVAL_STATUS", CommonConstants.UN_SUBMIT)//
    //                    .eq("CONFIRM_STATUS", CommonConstants.CONFIRM)
    //                    .eq("DEL_FLAG","0"));
    //            if(CollectionUtil.isNotEmpty(marketingTickets)){
    //                QueryWrapper<SwStMarketingTicketGroupSell> swStMarketingTicketGroupSellQueryWrapper=new QueryWrapper<>();
    //                swStMarketingTicketGroupSellQueryWrapper.select("ifnull(sum(discount_amount),0) as discount_amount");//*100
    //                swStMarketingTicketGroupSellQueryWrapper.eq("relation_id",marketingTickets.get(0).getId());
    //                swStMarketingTicketGroupSellQueryWrapper.eq("del_flag",0);
    //                String[] pay_method={"0"}; //现金
    //                swStMarketingTicketGroupSellQueryWrapper.in("pay_method",pay_method);
    //                List<Map<String, Object>> groupMaps = swStMarketingTicketGroupSellMapper.selectMaps(swStMarketingTicketGroupSellQueryWrapper);//团购的
    //                if(groupMaps!=null && groupMaps.size()>0){
    //                    Map<String, Object> res = groupMaps.get(0);
    //                    BigDecimal discount_amount = (BigDecimal)res.get("discount_amount");
    //                    marketTicketAmount=marketTicketAmount.add(discount_amount);
    //                }
    //                QueryWrapper<SwStMarketingTicketOffineSell> swStMarketingTicketOffineSellQueryWrapper=new QueryWrapper<>();
    //                swStMarketingTicketOffineSellQueryWrapper.select("ifnull(sum(CASH_SELL_AMOUNT),0) as cash_sell_amount");//*100
    //                swStMarketingTicketOffineSellQueryWrapper.eq("relation_id",marketingTickets.get(0).getId());
    //                swStMarketingTicketOffineSellQueryWrapper.eq("del_flag",0);
    //                List<Map<String, Object>> map2 = swStMarketingTicketOffineSellMapper.selectMaps(swStMarketingTicketOffineSellQueryWrapper);//现金
    //                if(map2!=null && map2.size()>0){
    //                    Map<String, Object> res = map2.get(0);
    //                    BigDecimal cash_sell_amount = (BigDecimal)res.get("cash_sell_amount");
    //                    marketTicketAmount=marketTicketAmount.add(cash_sell_amount);
    //                }
    //            }
    //
    //            //预制单程票
    //            BigDecimal singleTicketAmount=new BigDecimal(0);
    //            List<SwStTicketPettyAdd> pettyAdds = swStTicketPettyAddService.list(new QueryWrapper<SwStTicketPettyAdd>()
    //                    .eq("DATE_FORMAT(WORKING_END_TIME, '%Y-%m-%d')",merge.getSettleTime())
    //                    .eq("LINE_CODE", merge.getLineCode())
    //                    .eq("STATION_CODE", merge.getStationCode())
    //                    .eq("ns_job_no", merge.getConductorJobNo())
    //                    .eq("ns_shift", merge.getConductorShifts())
    //                    .eq("device_operate_num", merge.getDeviceOperateNum())
    //                    .eq("DEVICE_ATTRIBUTION", 1)//已归还
    //                    .eq("CONFIRM_STATUS", CommonConstants.CONFIRM)
    //                    .eq("DEL_FLAG","0"));
    //            if(CollectionUtil.isNotEmpty(pettyAdds)){
    //                QueryWrapper<SwStTicketPettyAddDetails> swStTicketPettyAddDetailsQueryWrapper=new QueryWrapper<>();
    //                swStTicketPettyAddDetailsQueryWrapper.select("sum( ( WINDOWS_NUM - WINDOWS_CLOSE_NUM - INVALID_TICKET_NUM ) * TICKET_VALUE ) amount");
    //                swStTicketPettyAddDetailsQueryWrapper.eq("relation_id",pettyAdds.get(0).getId());
    //                swStTicketPettyAddDetailsQueryWrapper.eq("del_flag",0);
    //                swStTicketPettyAddDetailsQueryWrapper.eq("type",'2');
    //                swStTicketPettyAddDetailsQueryWrapper.eq("ticket_name","YZDCP");
    //                List<Map<String, Object>> sqlPetty = swStTicketPettyAddDetailsService.getBaseMapper().selectMaps(swStTicketPettyAddDetailsQueryWrapper);
    //                //其他乘客事务金额
    //                QueryWrapper<SwStInputPassengerWorkTicket> inputPassengerWorkTicketQueryWrapper=new QueryWrapper<>();
    //                swStTicketPettyAddDetailsQueryWrapper.select("ifnull(sum(TICKET_PRICE),0) as amount");
    //                inputPassengerWorkTicketQueryWrapper.eq("DATE_FORMAT(HANDLE_TIME, '%Y-%m-%d')", merge.getSettleTime());
    //                inputPassengerWorkTicketQueryWrapper.eq("LINE_CODE", merge.getLineCode());
    //                inputPassengerWorkTicketQueryWrapper.eq("STATION_CODE", merge.getStationCode());
    //                inputPassengerWorkTicketQueryWrapper.eq("OPERATION_TYPE", '0');
    //                inputPassengerWorkTicketQueryWrapper.eq("HANDLE_TYPE", '1');
    //                inputPassengerWorkTicketQueryWrapper.eq("REPLACE_TICKET_TYPE", "YZDCP");
    //                inputPassengerWorkTicketQueryWrapper.eq("DEVICE_OPERATE_NUM", merge.getDeviceOperateNum());
    //                inputPassengerWorkTicketQueryWrapper.eq("HANDLE_PERSON_CODE", merge.getConductorJobNo());
    //                inputPassengerWorkTicketQueryWrapper.eq("CLASS_NUMBER", merge.getConductorShifts());
    //                inputPassengerWorkTicketQueryWrapper.eq("CONFIRM_STATUS", CommonConstants.CONFIRM);
    //                inputPassengerWorkTicketQueryWrapper.eq("DEL_FLAG", "0");
    //                List<Map<String, Object>> sqlTicketOther = swStInputPassengerWorkTicketService.getBaseMapper().selectMaps(inputPassengerWorkTicketQueryWrapper);
    //                if(sqlPetty!=null && sqlPetty.size()>0){
    //                    Map<String, Object> res = sqlPetty.get(0);
    //                    singleTicketAmount = singleTicketAmount.add((BigDecimal) res.get("amount"));
    //                }
    //                if(sqlTicketOther!=null && sqlTicketOther.size()>0){
    //                    Map<String, Object> res = sqlTicketOther.get(0);
    //                    BigDecimal amount = (BigDecimal) res.get("amount");
    //                    singleTicketAmount = singleTicketAmount.subtract(amount);
    //                }
    //            }
                BigDecimal marketTicketAmount = new BigDecimal("0");
                BigDecimal singleTicketAmount = new BigDecimal("0");
                BigDecimal emergencyAmount = new BigDecimal("0");
                BigDecimal passengerWorkAmount = new BigDecimal("0");
                Integer haveBus = null;
                Integer haveMarket = null;
                if(normal){//补提交查询
                    Date startTimeD=DateFormat.LocalDateToUdate(merge.getSettleTime());
                    Date endTimeD=DateFormat.LocalDateToUdate(merge.getSettleTime());
                    //利用Calendar 实现 Date日期+1天
                    Calendar c = Calendar.getInstance();
                    c.setTime(endTimeD);
                    c.add(Calendar.DAY_OF_MONTH, 1);
                    endTimeD = c.getTime();
                    String startTime=DateFormat.date_ex_str(startTimeD,"yyyy-MM-dd")+" 02:00:00";
                    String endTime=DateFormat.date_ex_str(endTimeD,"yyyy-MM-dd")+" 01:59:59";
                    param.put("startTime",startTime);
                    param.put("endTime",endTime);

                    //营销车票补提交
                    BigDecimal marketTicketAmountRepair = BomUtil.getMarketTicketAmountRepair(param);
                    if(marketTicketAmountRepair != null){
                        marketTicketAmount = marketTicketAmount.add(marketTicketAmountRepair);
                    }

                    //单程票补提交
                    BigDecimal singleTicketAmountRepair = BomUtil.getSingleTicketAmount(param);
                    if(singleTicketAmountRepair != null ){
                        singleTicketAmount = singleTicketAmount.add(singleTicketAmountRepair);
                    }
                    //应急纸票补提交
                    BigDecimal emergencyAmountRepair = BomUtil.getEmergencyAmount(param);
                    if(emergencyAmountRepair != null ){
                        emergencyAmount = emergencyAmount.add(emergencyAmountRepair);
                    }

                    //乘客事务补提交
                    List<Map<String, Object>> passengerWorkAmountList = BomUtil.getPassengerWorkAmountRepair(param,merge);
                    if(!CollectionUtils.isEmpty(passengerWorkAmountList)){
                        BigDecimal amount = (BigDecimal) passengerWorkAmountList.get(0).get("amount");
                        if(amount != null){
                            passengerWorkAmount = passengerWorkAmount.add(amount);
                        }
                    }

                    haveBus = BomUtil.isHaveBusRepair(param,merge);
                    haveMarket = BomUtil.isHaveMarketRepair(param,merge);
                }else {//正常提交查询
                    if(StringUtils.isNotEmpty(paramStar)){
                        JSONObject jsonObject = JSONObject.parseObject(paramStar);
                        param.put("startTime",jsonObject.get("startTime"));
                        param.put("endTime",jsonObject.get("endTime"));
                    }

                    //营销车票正常提交
                    BigDecimal marketTicketAmountNormal = BomUtil.getMarketTicketAmount(param);
                    if(marketTicketAmountNormal != null){
                        marketTicketAmount = marketTicketAmount.add(marketTicketAmountNormal);
                    }

                    //单程票金额正常提交
                    BigDecimal singleTicketAmountNormal = BomUtil.getSingleTicketAmount(param);//单程票
                    if(singleTicketAmountNormal != null ){
                        singleTicketAmount = singleTicketAmount.add(singleTicketAmountNormal);
                    }

                    //应急纸票补提交
                    BigDecimal emergencyAmountNormal = BomUtil.getEmergencyAmount(param);
                    if(emergencyAmountNormal != null ){
                        emergencyAmount = emergencyAmount.add(emergencyAmountNormal);
                    }


                    //乘客事务正常提交
                    List<Map<String, Object>> passengerWorkAmountList = BomUtil.getPassengerWorkAmount(param,merge);
                    if(!CollectionUtils.isEmpty(passengerWorkAmountList)){
                        BigDecimal amount = (BigDecimal) passengerWorkAmountList.get(0).get("amount");
                        if(amount != null){
                            passengerWorkAmount = passengerWorkAmount.add(amount);
                        }
                    }

                    haveBus = BomUtil.isHaveBus(param,merge);
                    haveMarket = BomUtil.isHaveMarketRepair(param,merge);
                }

                map.put("merge",JSONObject.toJSONString(merge));
                map.put("marketTicketAmount",marketTicketAmount.toString());
                map.put("passengerWorkAmount",passengerWorkAmount.toString());
                map.put("singleTicketAmount",singleTicketAmount.toString());
                map.put("emergencyAmount",emergencyAmount.toString());
                map.put("haveBus",haveBus.toString());
                map.put("haveMarket",haveMarket.toString());
                return R.ok(map);
            }
            return R.ok();
        } catch (ParseException e) {
            e.printStackTrace();
            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            return R.failed();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            //设置手动回滚
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            return R.failed();
        }

    }

    /**
     * 日结算通过被合并的数据ID查询合并之前的记录
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过被合并的数据ID查询合并之前的记录", notes = "通过被合并的数据ID查询合并之前的记录")
    @GetMapping("getMergeBeforById/{id}")
    public R getMergeBeforById(@PathVariable("id") Integer id) {
        SwStConductorSettle conductorSettle = swStConductorSettleService.getById(id);
        if(ObjectUtil.isNotEmpty(conductorSettle)){
            String isBeMergedId = conductorSettle.getIsBeMergedId();
            String[] split = isBeMergedId.split(",");
            List<SwStConductorSettle> list = swStConductorSettleMapper.getList(split);
            return R.ok(list);
        }else {
            return R.failed("无合并数据！");
        }
    }

    /**
     * 导出
     * @param
     * @return
     */
    @ApiOperation(value = "导出,settleTime(日期) 必选", notes = "导出,settleTime(日期) 必选")
    @GetMapping({"/dataExport"})
    public void export(SwStConductorSettle dto, HttpServletResponse response) {
        if(dto.getSettleTime() == null){
            return ;
        }
        swStConductorSettleService.export(dto,response);
    }

}
